import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
import { copyFileSync, mkdirSync, existsSync, readdirSync, statSync, readFileSync, writeFileSync } from 'fs';

// Helper function to copy directories recursively
function copyRecursiveSync(src, dest) {
  const exists = existsSync(src);
  const stats = exists && statSync(src);
  const isDirectory = exists && stats.isDirectory();
  
  if (isDirectory) {
    if (!existsSync(dest)) {
      mkdirSync(dest, { recursive: true });
    }
    readdirSync(src).forEach(childItemName => {
      copyRecursiveSync(
        resolve(src, childItemName),
        resolve(dest, childItemName)
      );
    });
  } else {
    const destDir = resolve(dest, '..');
    if (!existsSync(destDir)) {
      mkdirSync(destDir, { recursive: true });
    }
    copyFileSync(src, dest);
  }
}

export default defineConfig({
  plugins: [
    react(),
    {
      name: 'copy-assets',
      closeBundle() {
        // Copy data files to dist
        const dataFiles = ['data/longevity-content.js', 'data/default-reminders.js'];
        const distDataDir = resolve(__dirname, 'dist/data');
        
        if (!existsSync(distDataDir)) {
          mkdirSync(distDataDir, { recursive: true });
        }
        
        dataFiles.forEach(file => {
          const src = resolve(__dirname, file);
          const dest = resolve(distDataDir, file.split('/').pop());
          if (existsSync(src)) {
            copyFileSync(src, dest);
            console.log(`✓ Copied ${file}`);
          }
        });
        
        // Copy icons directory
        const iconsSrc = resolve(__dirname, 'icons');
        const iconsDest = resolve(__dirname, 'dist/icons');
        if (existsSync(iconsSrc)) {
          copyRecursiveSync(iconsSrc, iconsDest);
          console.log('✓ Copied icons directory');
        }
        
        // Copy and fix manifest.json (remove dist/ prefix from paths if present)
        const manifestSrc = resolve(__dirname, 'manifest.json');
        const manifestDest = resolve(__dirname, 'dist/manifest.json');
        if (existsSync(manifestSrc)) {
          const manifestContent = readFileSync(manifestSrc, 'utf8');
          const manifest = JSON.parse(manifestContent);
          
          // Remove 'dist/' prefix from all paths if present (for compatibility)
          // Since manifest.json will be in dist/, paths should be relative to dist/
          if (manifest.background && manifest.background.service_worker) {
            manifest.background.service_worker = manifest.background.service_worker.replace(/^dist\//, '');
          }
          if (manifest.action && manifest.action.default_popup) {
            manifest.action.default_popup = manifest.action.default_popup.replace(/^dist\//, '');
          }
          if (manifest.options_page) {
            manifest.options_page = manifest.options_page.replace(/^dist\//, '');
          }
          
          writeFileSync(manifestDest, JSON.stringify(manifest, null, 2));
          console.log('✓ Copied and fixed manifest.json');
        } else {
          console.warn('⚠ manifest.json not found in root directory');
        }
      }
    }
  ],
  build: {
    outDir: 'dist',
    rollupOptions: {
      input: {
        popup: resolve(__dirname, 'popup.html'),
        newtab: resolve(__dirname, 'newtab.html'),
        breathing: resolve(__dirname, 'breathing.html'),
        history: resolve(__dirname, 'longevity-history.html'),
        background: resolve(__dirname, 'src/background/main.js')
      },
      output: {
        entryFileNames: (chunkInfo) => {
          if (chunkInfo.name === 'background') {
            return 'background.js';
          }
          return 'assets/[name]-[hash].js';
        },
        chunkFileNames: 'assets/[name]-[hash].js',
        assetFileNames: (assetInfo) => {
          if (assetInfo.name === 'popup.html' || assetInfo.name === 'newtab.html' || 
              assetInfo.name === 'breathing.html' || assetInfo.name === 'longevity-history.html') {
            return '[name][extname]';
          }
          return 'assets/[name]-[hash].[ext]';
        }
      }
    },
    emptyOutDir: true
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
});
